// 时间格式化
// 日期转换
export const formatDate = (date, fmt) => {
  fmt = fmt.replace(/(Y+)/g, item => {
    return (date.getFullYear() + '').substr(4 - item.length)
  })
  let o = {
    'M+': date.getMonth() + 1,
    'D+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds()
  }
  for (let k in o) {
    let pattern = new RegExp(`(${k})`)
    fmt = fmt.replace(pattern, item => {
      return formatNumber(o[k])
    })
  }
  return fmt
}

export const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

export const getParamsStr = options => {
  let queryParams = []
  for (let key in options) {
    queryParams.push(key + '=' + options[key])
  }
  return queryParams.length > 0 ? '?' + queryParams.join('&') : ''
}

export const detalTime = (dateline) => {
  let nowTime = new Date()

  let oldTime = parseInt(dateline)

  let timeDif = nowTime / 1000 - oldTime

  if (timeDif < 60) return Math.floor(timeDif) + '秒前'

  if ((timeDif /= 60) < 60) return Math.floor(timeDif) + '分钟前'

  if ((timeDif /= 60) < 24) return Math.floor(timeDif) + '小时前'

  if ((timeDif /= 24) < 30) return Math.floor(timeDif) + '天前'

  if ((timeDif /= 30) < 12) return Math.floor(timeDif) + '月前'

  return Math.floor(timeDif / 12) + '年前'
}
